import request from './request';
import { checkingNeedToken } from "./evn";
import { alertMessage, getStore, setStore } from "./myUtil";
/**
 * 请求拦截 ---- 此方法返回的是一个Promise对象
 * @param {*} method    //  请求方式
 * @param {*} url       //  请求的url
 * @param {*} data      //  请求的参数
 * @param {*} dataType  //  请求的数据类型默认为json
 * @param {*} urlType   //  请求的baseUrl类型默认work
 */
let refreshParams = {
    grant_type:    "refresh_token",
    scope:         "select",
    client_id:     "web_password",
    client_secret: "workplan-manager",
    refresh_token: window.localStorage.getItem("wpsmRefreshToken"),  //refresh----token
};
// 去登陆并去除登录信息
function toLogin(text,type){
    alertMessage(text || "请求失败！",type || 'warning');
    REMOVELOGINMSG();
    setTimeout(function(){
        window.location.href = window.location.origin + '/wpsmt/login';
    },800);
}
export default function SENDAXIOS(method, url, data, dataType = 'json') {
    let checkMYpass = new Promise((resolve, reject) => {
        let oauthToken = () => { //从新刷新accessToken
            request('posturl', "oauth/token", refreshParams, dataType).then((res) => {
                if(res && res.status == "20000"){
                    toLogin("登录过期，请重新登录！"); //refresh----token过期或者失效；
                    return;
                }else{
                    if(res && res.access_token){
                        setStore('wpsmAccessToken', res.token_type + " " + res.access_token);
                        setStore('wpsmRefreshToken', res.refresh_token);
                        setStore('wpsmloginDate', moment(new Date()).valueOf());  //重置时间
                        resolve({ sign: "MYpass" });
                    }else{
                        reject(new Error('请求失败！'));
                        toLogin(res.message,'error');
                    }
                }
            }).catch(()=>{
                reject(new Error('请求失败！'));
                toLogin();
            })
        }
        if (checkingNeedToken(url)) {  //检测url是否需要token
            let loginData = getStore("wpsmloginDate");
            let newData = moment(new Date()).valueOf();
            if (loginData) {
                let runTime = parseInt((newData - loginData) / 1000);  //现在时间和登录时间相差的秒数
                let minute = Math.ceil(runTime / 60);
                if (minute > 27) {  //大与27分钟过期重新刷新token;
                    oauthToken();
                } else {
                    request(method, url, data, dataType).then((res) => {
                        if (res && res.status == "401") {  //过期
                            oauthToken();
                        } else {   //不过期
                            resolve(res)
                        }
                    })
                }
            } else {
                reject(new Error('没有登录！'));
                toLogin("登录信息失效，请重新登录！");
            }
        } else {    //不需要token的直接过滤掉；
            resolve({ sign: "MYpass" });
        }
    });
    return Promise.all([checkMYpass]).then((allRes) => {
        if (allRes[0].sign === "MYpass") {
            return request(method, url, data, dataType);
        } else {
            return Promise.resolve(allRes[0]);
        }
    })
}